package com.example.qxfw.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.example.qxfw.common.service.BaseService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class GenericDataListener<T>  implements ReadListener<T> {

    /**
     * 每隔5条存储数据库，然后清理List，方便内存回收
     */
    private static final int BATCH_COUNT =5;

    private List<T> dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private BaseService<T> service;

    public GenericDataListener(BaseService<T> service){
        this.service = service;
    }


    @Override
    public void invoke(T data, AnalysisContext context) {
        log.info("解析到一条数据：{}", data);
        dataList.add(data);
        if (dataList.size() >= BATCH_COUNT) {
            saveData();
            dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        service.save(dataList);
    }
}
